package com.ingrun.tuboshu.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.ingrun.tuboshu.entity.SysAdmin;
import com.ingrun.tuboshu.entity.vo.PasswordLoginQ;
import com.ingrun.tuboshu.entity.vo.UserListQ;
import com.ingrun.tuboshu.entity.vo.UpdPasswordQ;
import com.ingrun.tuboshu.mapper.SysAdminMapper;
import com.ingrun.tuboshu.service.ISysAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ingrun.tuboshu.utils.*;
import com.ingrun.tuboshu.utils.params.PageHelperList;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * <p>
 * 系统管理用户表	 服务实现类
 * </p>
 *
 * @author ingrun
 * @since 2025-01-23
 */
@Service
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements ISysAdminService {

    @Override
    public boolean register(SysAdmin sysAdmin) {
        sysAdmin.setPassword(PasswordUtil.encryptPassword(sysAdmin.getUsername(), sysAdmin.getPassword()));
        sysAdmin.setStatus("1");
        sysAdmin.setDelFlag("0");
        return this.save(sysAdmin);
    }

    @Override
    public String login(PasswordLoginQ query) {
        String username = query.getUsername().trim();
        SysAdmin dbUser = this.selectUserByUserName(username);
        if (dbUser == null) {
            ThreadUtil.execAsync(AsyncFactory.recordLogLogin("-1", username, "0", "用户名不正确", StpKit.ADMIN.getLoginType(), MDC.get("tl")));
            throw new ResponseException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR, "用户名不正确");
        }

        if (!dbUser.getStatus().equals("1")) {
            ThreadUtil.execAsync(AsyncFactory.recordLogLogin(dbUser.getId(), username, "0", ResponseEnum.USER_DISABLED_ERROR.getMessage(), StpKit.ADMIN.getLoginType(), MDC.get("tl")));
            throw new ResponseException(ResponseEnum.USER_DISABLED_ERROR);
        }

        if (PasswordUtil.checkPassword(username, query.getPassword(), dbUser.getPassword())) {
            StpKit.ADMIN.login(dbUser.getId());

            dbUser.setPassword(null);
            StpKit.ADMIN.getSession().set("user", dbUser);
            ThreadUtil.execAsync(AsyncFactory.recordLogLogin(dbUser.getId(), username, "1", "登录成功", StpKit.ADMIN.getLoginType(), MDC.get("tl")));
            return StpKit.ADMIN.getTokenValue();
        }

        ThreadUtil.execAsync(AsyncFactory.recordLogLogin(dbUser.getId(), username, "0", "密码校验不通过", StpKit.ADMIN.getLoginType(), MDC.get("tl")));
        throw new ResponseException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR, "密码校验不通过");
    }

    @Override
    public SysAdmin selectUserByUserName(String username) {
        LambdaQueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<SysAdmin>().lambda().eq(SysAdmin::getUsername, username);
        return this.getOne(queryWrapper, false);
    }

    @Override
    public boolean updatePassword(UpdPasswordQ query) {
//        String loginId = StpKit.ADMIN.getLoginIdAsString();

//        if (!loginId.equals(query.getId())) {
//            throw new ResponseException(ResponseEnum.REQUEST_PARAM_ERROR, "不能修改其他人的密码");
//        }

        SysAdmin dbUser = this.getById(query.getId());
        if (dbUser == null) {
            throw new ResponseException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR, "用户不存在");
        }

        if (!PasswordUtil.checkPassword(dbUser.getUsername(), query.getOldPassword(), dbUser.getPassword())) {
            throw new ResponseException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR, "旧密码不正确");
        }

        SysAdmin sysAdmin = new SysAdmin();
        sysAdmin.setId(query.getId());
        sysAdmin.setPassword(PasswordUtil.encryptPassword(dbUser.getUsername(), query.getNewPassword()));
        return this.updateById(sysAdmin);
    }

    @Override
    public SysAdmin getLonginUser() {
        return (SysAdmin) StpKit.ADMIN.getSession().get("user");
    }

    @Override
    public PageHelperList<SysAdmin> userList(UserListQ query) {
        if (query == null || query.getPage() <= 0 || query.getPageSize() <= 0) {
            return new PageHelperList<>(Collections.emptyList());
        }

        LambdaQueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<SysAdmin>().lambda()
                .like(StrUtil.isNotEmpty(query.getNickname()), SysAdmin::getNickname, query.getNickname())
                .like(StrUtil.isNotEmpty(query.getUsername()), SysAdmin::getUsername, query.getUsername())
                .like(StrUtil.isNotEmpty(query.getPhoneNumber()), SysAdmin::getPhoneNumber, query.getPhoneNumber())
                .like(StrUtil.isNotEmpty(query.getEmail()), SysAdmin::getEmail, query.getEmail())
                .eq(StrUtil.isNotEmpty(query.getStatus()), SysAdmin::getStatus, query.getStatus())
                .eq(StrUtil.isNotEmpty(query.getSex()), SysAdmin::getSex, query.getSex())
                .select(SysAdmin.class, i -> !i.getColumn().equals("password"));  // 查询去除password字段

        PageHelper.startPage(query.getPage(), query.getPageSize());
        return new PageHelperList<>(this.list(queryWrapper));
    }
}
